package com.csp.main.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csp.common.utils.R;
import com.csp.main.entity.Friends;
import com.csp.main.service.FriendsService;
import com.csp.main.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.management.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * <p>
 * 好友 前端控制器
 * </p>
 *
 * @author csp
 * @since 2022-06-18
 */
@RestController
@RequestMapping("/main/friends")
public class FriendsController {

    @Autowired
    private FriendsService friendsService;

    @GetMapping("/list")
    public R list(HttpServletRequest request){
        String token = request.getHeader(JWTUtils.USER_LOGIN_TOKEN);
        String userId = JWTUtils.validateToken(token);
        QueryWrapper<Friends> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("gmt_modified");
        queryWrapper.eq("user_id",userId);
        List<Friends> list = friendsService.list(queryWrapper);
        return R.ok().data("rows",list);
    }

    @DeleteMapping("/delete/{friendsId}")
    public R delete(HttpServletRequest request, @PathVariable String friendsId){
        String token = request.getHeader(JWTUtils.USER_LOGIN_TOKEN);
        String userId = JWTUtils.validateToken(token);
        QueryWrapper<Friends> queryWrapper = new QueryWrapper<>();
        queryWrapper.and(friendsQueryWrapper -> friendsQueryWrapper.eq("user_id",userId).eq("friend_id",friendsId));
        boolean remove = friendsService.remove(queryWrapper);
        return remove?R.ok():R.error();
    }

    @GetMapping("/add/{friendId}")
    public R add(HttpServletRequest request,@PathVariable String friendId){
        String token = request.getHeader(JWTUtils.USER_LOGIN_TOKEN);
        String userId = JWTUtils.validateToken(token);

        QueryWrapper<Friends> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.eq("friend_id",friendId);
        List<Friends> list = friendsService.list(queryWrapper);
        if (list.size()>0){
            return R.error();
        }
        Friends friend1 = new Friends();
        friend1.setUserId(userId);
        friend1.setFriendId(friendId);
        boolean save1 = friendsService.save(friend1);
        Friends friend2 = new Friends();
        friend2.setUserId(friendId);
        friend2.setFriendId(userId);
        boolean save2 = friendsService.save(friend2);
        return save1&&save2?R.ok():R.error();
    }

}

